package com.jake.eurekaclient.controller;

import com.jake.mallmodel.entity.User;
import com.jake.mallmodel.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("users")
@SuppressWarnings("unchecked")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String MALL_CRUD_USERS_URL = "http://mall-crud/users/";

    @GetMapping
    public List<User> getUsers() {
        List<User> users = restTemplate.getForObject(MALL_CRUD_USERS_URL, List.class);
        return users;
    }

    @GetMapping("info")
    public List<UserInfo> getAllUserInfo() {
        List<UserInfo> allUserInfo = restTemplate.getForObject(MALL_CRUD_USERS_URL + "info/", List.class);
        return allUserInfo;
    }

    @GetMapping("{uid}")
    public User getUserById(@PathVariable Integer uid) {
        User user = restTemplate.getForObject(MALL_CRUD_USERS_URL + uid, User.class);
        return user;
    }

    @GetMapping("info/{uid}")
    public UserInfo getUserInfoById(@PathVariable Integer uid) {
        UserInfo userInfo = restTemplate.getForObject(MALL_CRUD_USERS_URL + "info/" + uid, UserInfo.class);
        return userInfo;
    }

    @GetMapping("info/{cname}/{username}")
    public List<UserInfo> getUserInfoByUsernameAndCname(@PathVariable String username, @PathVariable String cname) {
        List<UserInfo> userInfoList = restTemplate.getForObject(MALL_CRUD_USERS_URL + "info/" + cname + "/" + username, List.class);
        return userInfoList;
    }

    @PostMapping
    public String addUser(@RequestBody User user) {
        String msg = restTemplate.postForObject(MALL_CRUD_USERS_URL, user, String.class);
        return msg;
    }

    @PutMapping
    public void updateUser(@RequestBody User user) {
        restTemplate.put(MALL_CRUD_USERS_URL, user);
    }

    @DeleteMapping("{uid}")
    public void deleteUserById(@PathVariable Integer uid) {
        restTemplate.delete(MALL_CRUD_USERS_URL + uid);
    }

}
